<template>
  <div class="auto-complete">
    <el-autocomplete
      v-model="state1"
      class="inline-input"
      :fetch-suggestions="querySearch"
      placeholder="请输入内容"
      clearable
      :disabled="disabled"
      @select="handleSelect"
      @input="sendDataToFather()"
      @clear="deleteShowData()"
    />
  </div>
</template>
<script>
export default {
  name: 'AutoComplete',
  props: {
    suggestions: {
      type: Array,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: []
    },
    position: {
      type: Object,
      required: true
    },
    disabled: {
      type: Boolean,
      required: true
    },
    inputContent: {
      type: Object,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: {}
    }
  },
  data() {
    return {
      state1: '',
      id: ''
    };
  },
  watch: {
    inputContent(newValue, oldValue) {
      this.state1 = this.inputContent.param;
    }
  },
  methods: {
    // querySearch(queryString, cb) {
    //   this.suggestions.forEach(suggestion => {
    //     suggestion.value = suggestion.propertyValue;
    //   });
    //   cb(this.suggestions);
    // },
    querySearch(queryString, cb) {
      this.suggestions.forEach(suggestion => {
        suggestion.value = suggestion.propertyValue;
      });
      var results = queryString
        ? this.suggestions.filter(this.createFilter(queryString))
        : this.suggestions;
      // 调用 callback 返回建议列表的数据
      for (const item of this.suggestions) {
        if (item.value === queryString) {
          this.id = results[0].id;
          const param = {
            position: this.position,
            model: this.state1,
            id: this.id
          };
          this.$emit('showChangeData', param);
        }
      }
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.propertyValue
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect(resItem) {
      for (const item of this.suggestions) {
        if (item.value === resItem.propertyValue) {
          this.id = resItem.id;
          const param = {
            position: this.position,
            model: this.state1,
            id: this.id
          };
          this.$emit('showChangeData', param);
        }
      }
      this.$emit('selected', resItem);
    },
    // 给父组件传送位置信息和输入信息
    sendDataToFather() {
      const param = {
        position: this.position,
        model: this.state1,
        id: ''
      };
      this.$emit('showChangeData', param);
    },
    // 点击删除
    deleteShowData() {
      this.state1 = '';
      this.$emit('deleteShow', this.position);
    }
  }
};
</script>
